<?php
/**
 * 该文件定义一些可以被公用的函数，与业务逻辑完全分离
 */

/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $start      截取的起始位置
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */
function sub_str($str, $start = 0, $length = 0, $append = true)
{
    $str = trim($str);
    if ($length == 0) {
        return $str;
    }
    
    if (function_exists('mb_substr')) {
        $newstr = mb_substr($str, $start, $length, 'UTF-8');
    } else {
        $strlength = strlen($str);
        
        if ($length < 0) {
            $length = $strlength + $length;
        } elseif ($length >= $strlength) {
            return $str;
        }
        $newstr = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $start . '}((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $length . '}).*#s', '$1', $str);
    }
    
    if ($append && $str != $newstr) {
        $newstr .= '...';
    }
    
    return $newstr;
}

/**
 * 去除字符串右侧可能出现的乱码
 *
 * @param   string      $str        字符串
 *
 * @return  string
 */
function trim_right($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]+/', '', $str)) % 3;
    
    if ($length > 0) {
        $str = substr($str, 0, 0 - $length);
    }
    
    return $str;
}

/**
 * 计算字符串的长度（汉字按照两个字符计算）
 *
 * @param   string      $str        字符串
 *
 * @return  int
 */
function str_len($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));
    
    if ($length) {
        return strlen($str) - $length + intval($length / 3) * 2;
    } else {
        return strlen($str);
    }
}

/**
 * 获得用户操作系统的换行符
 *
 * @access  public
 * @return  string
 */
function get_crlf()
{
    /* LF (Line Feed, 0x0A, \N) 和 CR(Carriage Return, 0x0D, \R) */
    if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win')) {
        $the_crlf = '\r\n';
    } elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac')) {
        $the_crlf = '\r'; // for old MAC OS
    } else {
        $the_crlf = '\n';
    }
    
    return $the_crlf;
}

/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 * @author   Xuan Yan
 *
 * @return   void
 */
function db_create_in($item_list, $field_name = '')
{
    if (empty($item_list)) {
        return $field_name . " IN ('') ";
    } else {
        if (!is_array($item_list)) {
            $item_list = explode(',', $item_list);
        }
        $item_list = array_unique($item_list);
        $item_list_tmp = '';
        foreach ($item_list as $item) {
            if ($item !== '') {
                $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
            }
        }
        if (empty($item_list_tmp)) {
            return $field_name . " IN ('') ";
        } else {
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }
    }
}

/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;
    
    if ($realip !== NULL) {
        return $realip;
    }
    
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            
            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr as $ip) {
                $ip = trim($ip);
                
                if ($ip != 'unknown') {
                    $realip = $ip;
                    
                    break;
                }
            }
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            if (isset($_SERVER['REMOTE_ADDR'])) {
                $realip = $_SERVER['REMOTE_ADDR'];
            } else {
                $realip = '0.0.0.0';
            }
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        } else {
            $realip = getenv('REMOTE_ADDR');
        }
    }
    
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    
    return $realip;
}

/**
 * 验证输入的邮件地址是否合法
 *
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 *
 * @return bool
 */
function is_email($email)
{
    $pattern = '/([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/';
    
    return preg_match($pattern, $email);
}

/**
 * 检查是否为一个合法的时间格式
 *
 * @access  public
 * @param   string  $time
 * @return  void
 */
function is_time($time)
{
    $pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';
    
    return preg_match($pattern, $time);
}

/**
 * 获得查询时间和次数，并赋值给smarty
 *
 * @access  public
 * @return  void
 */
function assign_query_info()
{
    if ($GLOBALS['db']->queryTime == '') {
        $query_time = 0;
    } else {
        list($now_usec, $now_sec) = explode(' ', microtime());
        list($start_usec, $start_sec) = explode(' ', $GLOBALS['db']->queryTime);
        
        $query_time = ($now_sec - $start_sec) + ($now_usec - $start_usec);
        $query_time = number_format($query_time, 6);
    }
    $GLOBALS['smarty']->assign('query_info', sprintf($GLOBALS['_LANG']['query_info'], $GLOBALS['db']->queryCount, $query_time));
    
    /* 内存占用情况 */
    if ($GLOBALS['_LANG']['memory_info'] && function_exists('memory_get_usage')) {
        $GLOBALS['smarty']->assign('memory_info', sprintf($GLOBALS['_LANG']['memory_info'], memory_get_usage() / 1024 / 1024));
    }

}

/**
 * 格式化商品价格
 *
 * @access  public
 * @param   float   $price  商品价格
 * @param 	int 	$format	价格格式
 * @return  string
 */
function price_format($price, $format = 0)
{
    switch ($format) {
        case 0 :
            $price = number_format($price, 2, '.', '');
            break;
        case 1 : // 保留不为 0 的尾数
            $price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', ''));
            
            if (substr($price, -1) == '.') {
                $price = substr($price, 0, -1);
            }
            break;
        case 2 : // 不四舍五入，保留1位
            $price = substr(number_format($price, 2, '.', ''), 0, -1);
            break;
        case 3 : // 直接取整
            $price = intval($price);
            break;
        case 4 : // 四舍五入，保留 1 位
            $price = number_format($price, 1, '.', '');
            break;
        case 5 : // 先四舍五入，不保留小数
            $price = round($price);
            break;
    }
    
    return sprintf($GLOBALS['_CFG']['currency_format'], $price);
}

/**
 * 文件或目录权限检查函数
 *
 * @access          public
 * @param           string  $file_path   文件路径
 * @param           bool    $rename_prv  是否在检查修改权限时检查执行rename()函数的权限
 *
 * @return          int     返回值的取值范围为{0 <= x <= 15}，每个值表示的含义可由四位二进制数组合推出。
 * 返回值在二进制计数法中，四位由高到低分别代表
 * 可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。
 */
function file_mode_info($file_path)
{
    /* 如果不存在，则不可读、不可写、不可改 */
    if (!file_exists($file_path)) {
        return false;
    }
    
    $mark = 0;
    
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
        /* 测试文件 */
        $test_file = $file_path . '/cf_test.txt';
        
        /* 如果是目录 */
        if (is_dir($file_path)) {
            /* 检查目录是否可读 */
            $dir = @opendir($file_path);
            if ($dir === false) {
                return $mark; //如果目录打开失败，直接返回目录不可修改、不可写、不可读
            }
            if (@readdir($dir) !== false) {
                $mark ^= 1; //目录可读 001，目录不可读 000
            }
            @closedir($dir);
            
            /* 检查目录是否可写 */
            $fp = @fopen($test_file, 'wb');
            if ($fp === false) {
                return $mark; //如果目录中的文件创建失败，返回不可写。
            }
            if (@fwrite($fp, 'directory access testing.') !== false) {
                $mark ^= 2; //目录可写可读011，目录可写不可读 010
            }
            @fclose($fp);
            
            @unlink($test_file);
            
            /* 检查目录是否可修改 */
            $fp = @fopen($test_file, 'ab+');
            if ($fp === false) {
                return $mark;
            }
            if (@fwrite($fp, "modify test.\r\n") !== false) {
                $mark ^= 4;
            }
            @fclose($fp);
            
            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false) {
                $mark ^= 8;
            }
            @unlink($test_file);
        } /* 如果是文件 */
        elseif (is_file($file_path)) {
            /* 以读方式打开 */
            $fp = @fopen($file_path, 'rb');
            if ($fp) {
                $mark ^= 1; //可读 001
            }
            @fclose($fp);
            
            /* 试着修改文件 */
            $fp = @fopen($file_path, 'ab+');
            if ($fp && @fwrite($fp, '') !== false) {
                $mark ^= 6; //可修改可写可读 111，不可修改可写可读011...
            }
            @fclose($fp);
            
            /* 检查目录下是否有执行rename()函数的权限 */
            if (@rename($test_file, $test_file) !== false) {
                $mark ^= 8;
            }
        }
    } else {
        if (@is_readable($file_path)) {
            $mark ^= 1;
        }
        
        if (@is_writable($file_path)) {
            $mark ^= 14;
        }
    }
    
    return $mark;
}

function log_write($arg, $file = '', $line = '')
{
    if ((DEBUG_MODE & 4) != 4) {
        return;
    }
    
    $str = "\r\n-- " . date('Y-m-d H:i:s') . " --------------------------------------------------------------\r\n";
    $str .= "FILE: $file\r\nLINE: $line\r\n";
    
    if (is_array($arg)) {
        $str .= '$arg = array(';
        foreach ($arg as $val) {
            foreach ($val as $key => $list) {
                $str .= "'$key' => '$list'\r\n";
            }
        }
        $str .= ")\r\n";
    } else {
        $str .= $arg;
    }
    
    file_put_contents(ROOT_PATH . 'data/log.txt', $str);
}

/**
 * 检查目标文件夹是否存在，如果不存在则自动创建该目录
 *
 * @access      public
 * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
 *
 * @return      bool
 */
function make_dir($folder)
{
    $reval = false;
    
    if (!file_exists($folder)) {
        /* 如果目录不存在则尝试创建该目录 */
        @umask(0);
        
        /* 将目录路径拆分成数组 */
        preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
        
        /* 如果第一个字符为/则当作物理路径处理 */
        $base = ($atmp[0][0] == '/') ? '/' : '';
        
        /* 遍历包含路径信息的数组 */
        foreach ($atmp[1] as $val) {
            if ('' != $val) {
                $base .= $val;
                
                if ('..' == $val || '.' == $val) {
                    /* 如果目录为.或者..则直接补/继续下一个循环 */
                    $base .= '/';
                    
                    continue;
                }
            } else {
                continue;
            }
            
            $base .= '/';
            
            if (!file_exists($base)) {
                /* 尝试创建目录，如果创建失败则继续循环 */
                if (@mkdir($base, 0777)) {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
        }
    } else {
        /* 路径已经存在。返回该路径是不是一个目录 */
        $reval = is_dir($folder);
    }
    
    clearstatcache();
    
    return $reval;
}

/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashes_deep($value)
{
    if (empty($value)) {
        return $value;
    } else {
        return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    }
}

/**
 * 将对象成员变量或者数组的特殊字符进行转义
 *
 * @access   public
 * @param    mix        $obj      对象或者数组
 * @author   Xuan Yan
 *
 * @return   mix                  对象或者数组
 */
function addslashes_deep_obj($obj)
{
    if (is_object($obj) == true) {
        foreach ($obj as $key => $val) {
            $obj->$key = addslashes_deep($val);
        }
    } else {
        $obj = addslashes_deep($obj);
    }
    
    return $obj;
}

/**
 * 递归方式的对变量中的特殊字符去除转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function stripslashes_deep($value)
{
    if (empty($value)) {
        return $value;
    } else {
        return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    }
}

/**
 * 创建分页的列表
 *
 * @access  public
 * @param   integer $count
 * @return  string
 */
function smarty_create_pages($params)
{
    extract($params);
    
    $str = '';
    $len = 10;
    
    if (empty($page)) {
        $page = 1;
    }
    
    if (!empty($count)) {
        $step = 1;
        $str .= "<option value='1'>1</option>";
        
        for($i = 2; $i < $count; $i += $step) {
            $step = ($i >= $page + $len - 1 || $i <= $page - $len + 1) ? $len : 1;
            $str .= "<option value='$i'";
            $str .= $page == $i ? " selected='true'" : '';
            $str .= ">$i</option>";
        }
        
        if ($count > 1) {
            $str .= "<option value='$count'";
            $str .= $page == $count ? " selected='true'" : '';
            $str .= ">$count</option>";
        }
    }
    
    return $str;
}

/**
 * 将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 *
 * @access  public
 * @param   string       $str         待转换字串
 *
 * @return  string       $str         处理后字串
 */
function make_semiangle($str)
{
    $arr = array(
            '０' => '0', 
            '１' => '1', 
            '２' => '2', 
            '３' => '3', 
            '４' => '4', 
            '５' => '5', 
            '６' => '6', 
            '７' => '7', 
            '８' => '8', 
            '９' => '9', 
            'Ａ' => 'A', 
            'Ｂ' => 'B', 
            'Ｃ' => 'C', 
            'Ｄ' => 'D', 
            'Ｅ' => 'E', 
            'Ｆ' => 'F', 
            'Ｇ' => 'G', 
            'Ｈ' => 'H', 
            'Ｉ' => 'I', 
            'Ｊ' => 'J', 
            'Ｋ' => 'K', 
            'Ｌ' => 'L', 
            'Ｍ' => 'M', 
            'Ｎ' => 'N', 
            'Ｏ' => 'O', 
            'Ｐ' => 'P', 
            'Ｑ' => 'Q', 
            'Ｒ' => 'R', 
            'Ｓ' => 'S', 
            'Ｔ' => 'T', 
            'Ｕ' => 'U', 
            'Ｖ' => 'V', 
            'Ｗ' => 'W', 
            'Ｘ' => 'X', 
            'Ｙ' => 'Y', 
            'Ｚ' => 'Z', 
            'ａ' => 'a', 
            'ｂ' => 'b', 
            'ｃ' => 'c', 
            'ｄ' => 'd', 
            'ｅ' => 'e', 
            'ｆ' => 'f', 
            'ｇ' => 'g', 
            'ｈ' => 'h', 
            'ｉ' => 'i', 
            'ｊ' => 'j', 
            'ｋ' => 'k', 
            'ｌ' => 'l', 
            'ｍ' => 'm', 
            'ｎ' => 'n', 
            'ｏ' => 'o', 
            'ｐ' => 'p', 
            'ｑ' => 'q', 
            'ｒ' => 'r', 
            'ｓ' => 's', 
            'ｔ' => 't', 
            'ｕ' => 'u', 
            'ｖ' => 'v', 
            'ｗ' => 'w', 
            'ｘ' => 'x', 
            'ｙ' => 'y', 
            'ｚ' => 'z', 
            '（' => '(', 
            '）' => ')', 
            '［' => '[', 
            '］' => ']', 
            '【' => '[', 
            '】' => ']', 
            '〖' => '[', 
            '〗' => ']', 
            '「' => '[', 
            '」' => ']', 
            '『' => '[', 
            '』' => ']', 
            '｛' => '{', 
            '｝' => '}', 
            '《' => '<', 
            '》' => '>', 
            '％' => '%', 
            '＋' => '+', 
            '—' => '-', 
            '－' => '-', 
            '～' => '-', 
            '：' => ':', 
            '。' => '.', 
            '、' => ',', 
            '，' => '.', 
            '、' => '.', 
            '；' => ',', 
            '？' => '?', 
            '！' => '!', 
            '…' => '-', 
            '‖' => '|', 
            '＂' => '"', 
            '＇' => '`', 
            '｀' => '`', 
            '｜' => '|', 
            '〃' => '"', 
            '　' => ' ');
    
    return strtr($str, $arr);
}

/**
 * 检查文件类型
 *
 * @access      public
 * @param       string      filename            文件名
 * @param       string      realname            真实文件名
 * @param       string      limit_ext_types     允许的文件类型
 * @return      string
 */
function check_file_type($filename, $realname = '', $limit_ext_types = '')
{
    if ($realname) {
        $extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
    } else {
        $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
    }
    
    $str = $format = '';
    
    $file = @fopen($filename, 'rb');
    if ($file) {
        $str = @fread($file, 0x400); // 读取前 1024 个字节
        @fclose($file);
    } else {
        if (stristr($filename, ROOT_PATH) === false) {
            if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' || $extname == 'xls' || $extname == 'txt' || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' || $extname == 'pdf' || $extname == 'rm' || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' || $extname == 'swf' || $extname == 'chm' || $extname == 'sql' || $extname == 'cert') {
                $format = $extname;
            }
        } else {
            return '';
        }
    }
    
    if ($format == '' && strlen($str) >= 2) {
        if (substr($str, 0, 4) == 'MThd' && $extname != 'txt') {
            $format = 'mid';
        } elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav') {
            $format = 'wav';
        } elseif (substr($str, 0, 3) == "\xFF\xD8\xFF") {
            $format = 'jpg';
        } elseif (substr($str, 0, 4) == 'GIF8' && $extname != 'txt') {
            $format = 'gif';
        } elseif (substr($str, 0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") {
            $format = 'png';
        } elseif (substr($str, 0, 2) == 'BM' && $extname != 'txt') {
            $format = 'bmp';
        } elseif ((substr($str, 0, 3) == 'CWS' || substr($str, 0, 3) == 'FWS') && $extname != 'txt') {
            $format = 'swf';
        } elseif (substr($str, 0, 4) == "\xD0\xCF\x11\xE0") { // D0CF11E == DOCFILE == Microsoft Office Document
            if (substr($str, 0x200, 4) == "\xEC\xA5\xC1\x00" || $extname == 'doc') {
                $format = 'doc';
            } elseif (substr($str, 0x200, 2) == "\x09\x08" || $extname == 'xls') {
                $format = 'xls';
            } elseif (substr($str, 0x200, 4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt') {
                $format = 'ppt';
            }
        } elseif (substr($str, 0, 4) == "PK\x03\x04") {
            $format = 'zip';
        } elseif (substr($str, 0, 4) == 'Rar!' && $extname != 'txt') {
            $format = 'rar';
        } elseif (substr($str, 0, 4) == "\x25PDF") {
            $format = 'pdf';
        } elseif (substr($str, 0, 3) == "\x30\0x82\0x0a") {
            $format = 'cert';
        } elseif (substr($str, 0, 4) == 'ITSF' && $extname != 'txt') {
            $format = 'chm';
        } elseif (substr($str, 0, 4) == "\x2ERMF") {
            $format = 'rm';
        } elseif ($extname == 'sql') {
            $format = 'sql';
        } elseif ($extname == 'txt') {
            $format = 'txt';
        }
    }
    
    if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false) {
        $format = '';
    }
    
    return $format;
}

/**
 * 获取服务器的ip
 *
 * @access      public
 *
 * @return string
 **/
function real_server_ip()
{
    static $serverip = NULL;
    
    if ($serverip !== NULL) {
        return $serverip;
    }
    
    if (isset($_SERVER)) {
        if (isset($_SERVER['SERVER_ADDR'])) {
            $serverip = $_SERVER['SERVER_ADDR'];
        } else {
            $serverip = '0.0.0.0';
        }
    } else {
        $serverip = getenv('SERVER_ADDR');
    }
    
    return $serverip;
}

/**
 * 向url中添加参数并返回添加参数后的url，参数名和参数值都会进行编码
 *
 * @author Zandy<yzhang@ouku.com>
 * 
 * @param string $url 处理前的URL
 * @param string $key 添加的参数名
 * @param string $value 添加的参数值
 *
 * @return string 添加完参数后的url
 **/
function add_param_in_url($url, $key, $value)
{
    return remove_param_in_url($url, $key, true) . urlencode($key) . '=' . urlencode($value);
}

/**
 * 从url中移除参数，并返回移除参数后的url
 *
 * @author Zandy<yzhang@ouku.com>
 * 
 * @param string $url 处理前的URL
 * @param string $pkey 需要移除的参数名
 * @param boolean $append 是否在尾部附加 ? 或 & 
 *
 * @return string 添加完参数后的url
 **/
function remove_param_in_url($url, $pkey, $append = false)
{
    $preg = '/[\?|&](' . preg_quote($pkey) . '=([^&=]*))/';
    $m = null;
    preg_match_all($preg, $url, $m);
    if (isset($m[1]) && is_array($m[1])) {
        foreach ($m[1] as $v) {
            $url = str_replace($v, "", $url);
        }
    }
    $url = str_replace(array("?&", "&&"), array("?", "&"), $url);
    $r = rtrim($url, ' &');
    if ($append) {
        if (strpos($r, '?') === false) {
            $r .= '?';
        }
        if (substr($r, -1) != '?' && substr($r, -1) != '&') {
            $r .= '&';
        }
    }
    return $r;
}

function imap_utf8_fix($obj)
{
    if (is_array($obj)) {
        foreach ($obj as $key => $item) {
            $obj[$key] = imap_utf8_fix($item);
        }
    } else if (is_object($obj)) {
        foreach ($obj as $key => $item) {
            $obj->$key = imap_utf8_fix($item);
        }
    } else {
        $obj = iconv_mime_decode($obj, 0, "UTF-8");
    }
    return $obj;
}

function check_option($option, $value)
{
    if (($option & $value) == $value) {
        return true;
    }
    return false;
}

// {{{ add funciton
function pp()
{
    $argvs = func_get_args();
    echo '<div style="text-align: left;">';
    foreach ($argvs as $k => $v) {
        echo "<xmp>";
        print_r($v);
        echo "</xmp>";
    }
    echo '</div>';
}
function vv()
{
    $argvs = func_get_args();
    echo '<div style="text-align: left;">';
    foreach ($argvs as $k => $v) {
        echo "<xmp>";
        var_dump($v);
        echo "</xmp>";
    }
    echo '</div>';
}

function build_url_str($str, $ex = ' ', $im = '-')
{
    $str = str_replace(array('  ', "\\", "/", '#', '&', "'", '"', ',', ':', '.', '[', ']', '(', ')'), ' ', $str);
    $str = ucwords(strtolower($str));
    $str = explode($ex, $str);
    $arr = array();
    foreach ($str as $v) {
        if ($v) {
            $arr[] = $v;
        }
    }
    // return strtolower(implode($im, $str));
    $url = implode($im, $arr);
    
    $foreign_characters = array(
            '/æ|ǽ/' => 'ae', 
            '/œ/' => 'oe', 
            '/Æ|Ǽ/' => 'AE', 
            '/ß/' => 'ss', 
            '/Ĳ/' => 'IJ', 
            '/ĳ/' => 'ij', 
            '/Œ/' => 'OE', 
            '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A', 
            '/à|á|â|ã|ä|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a', 
            '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', 
            '/ç|ć|ĉ|ċ|č/' => 'c', 
            '/Ð|Ď|Đ/' => 'D', 
            '/ð|ď|đ/' => 'd', 
            '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E', 
            '/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e', 
            '/ƒ/' => 'f', 
            '/Ĝ|Ğ|Ġ|Ģ/' => 'G', 
            '/ĝ|ğ|ġ|ģ/' => 'g', 
            '/Ĥ|Ħ/' => 'H', 
            '/ĥ|ħ/' => 'h', 
            '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I', 
            '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i', 
            '/Ĵ/' => 'J', 
            '/ĵ/' => 'j', 
            '/Ķ/' => 'K', 
            '/ķ/' => 'k', 
            '/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L', 
            '/ĺ|ļ|ľ|ŀ|ł/' => 'l', 
            '/Ñ|Ń|Ņ|Ň/' => 'N', 
            '/ñ|ń|ņ|ň|ŉ/' => 'n', 
            '/Ò|Ó|Ô|Õ|Ö|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O', 
            '/ò|ó|ô|õ|ö|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o', 
            '/Ŕ|Ŗ|Ř/' => 'R', 
            '/ŕ|ŗ|ř/' => 'r', 
            '/Ś|Ŝ|Ş|Š/' => 'S', 
            '/ś|ŝ|ş|š|ſ/' => 's', 
            '/Ţ|Ť|Ŧ/' => 'T', 
            '/ţ|ť|ŧ/' => 't', 
            '/Ù|Ú|Û|Ũ|Ü|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U', 
            '/ù|ú|û|ũ|ü|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u', 
            '/Ý|Ÿ|Ŷ/' => 'Y', 
            '/ý|ÿ|ŷ/' => 'y', 
            '/Ŵ/' => 'W', 
            '/ŵ/' => 'w', 
            '/Ź|Ż|Ž/' => 'Z', 
            '/ź|ż|ž/' => 'z');
    
    foreach ($foreign_characters as $k => $v) {
        $url = preg_replace($k, $v, $url);
    }
    return $url;
}

function calculate_date_diff($date1, $date2)
{
    $datetime1 = strtotime($date1);
    $datetime2 = strtotime($date2);
    $diff_days = ceil(($datetime2 - $datetime1) / 3600 / 24);
    return $diff_days;
}

function csv_parse($str, $f_delim = ',', $r_delim = "\n", $qual = '"')
{
    $output = array();
    $row = array();
    $word = '';
    
    $str = trim($str);
    $len = strlen($str);
    $inside = false;
    
    $skipchars = array($qual, "\\");
    for($i = 0; $i < $len; ++$i) {
        $c = $str[$i];
        if (!$inside && $c == $f_delim) {
            $row[] = $word;
            $word = '';
        } else if (!$inside && $c == $r_delim) {
            $row[] = $word;
            $word = '';
            $output[] = $row;
            $row = array();
        } else if ($inside && in_array($c, $skipchars) && ($i + 1 < $len && $str[$i + 1] == $qual)) {
            $word .= $qual;
            ++$i;
        } else if ($c == $qual) {
            $inside = !$inside;
        } else {
            $word .= $c;
        }
    }
    
    $row[] = $word;
    $output[] = $row;
    return $output;
}
?>